package main

import (
	"context"
	"fmt"
	greeter "go_final/demos/grpc_metadata/protofile"
	"net"
	"time"

	"google.golang.org/grpc"
)

type Greeter struct{}

func (g Greeter) SayHi(ctx context.Context, request *greeter.SayHiRequest) (*greeter.SayHiResponse, error) {
	time.Sleep(time.Second * 2)
	return &greeter.SayHiResponse{
		Reply: "I'm fine!",
	}, nil
}

func main() {
	// 1.生成拦截器
	interceptor := func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
		handler grpc.UnaryHandler) (resp interface{}, err error) {
		fmt.Println("接收到了一个请求")
		fmt.Printf("%#v \n", info)
		res, err := handler(ctx, req)
		fmt.Println("请求已经结束")
		return res, err
	}
	opt := grpc.UnaryInterceptor(interceptor)

	// 2.加入拦截器
	s := grpc.NewServer(opt)

	greeter.RegisterGreeterServer(s, &Greeter{})
	lis, err := net.Listen("tcp", ":8080")
	if err != nil {
		panic(err)
	}
	s.Serve(lis)
}
